package cn.thoughtworks.school.services;

import cn.thoughtworks.school.entities.Topic;
import cn.thoughtworks.school.repositories.TopicDiffRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static cn.thoughtworks.school.entities.Operation.COPY;
import static cn.thoughtworks.school.entities.Operation.CREATE;

@Service
public class TopicDiffService {
    @Autowired
    private TopicDiffRepository topicDiffRepository;

    public void updateTopicNotification(Map data) {
        Topic topic = Topic.build(data);
        updateTopicFromId(topic);
        topicDiffRepository.save(topic);
    }
    private void updateTopicFromId(Topic topic) {
        if (Objects.equals(CREATE, topic.getOperation()) || Objects.equals(COPY, topic.getOperation())) {
            return;
        }
        Long fromId = topicDiffRepository.findFirst1ByTopicIdOrderByIdDesc(topic.getTopicId()).getFromId();
        topic.setFromId(fromId);
    }

    public List<Topic> getLatestTopicsByProgramsId(List<Long> programIds) {
        return programIds.isEmpty()
            ? new ArrayList<>()
            : topicDiffRepository.findFirst1ByIdAndProgramIdInOrderByProgramsIdDesc(programIds);
    }
}
